package com.diy.sigmund.diyuser.service.impl;

import com.diy.sigmund.diycommon.entity.CustomUser;
import com.diy.sigmund.diycommon.entity.ResultMsg;
import com.diy.sigmund.diycommon.entity.po.user.UserAuth;
import com.diy.sigmund.diycommon.entity.po.user.UserBase;
import com.diy.sigmund.diycommon.spring.ContextHolder;
import com.diy.sigmund.diyuser.entity.dto.UserBaseDTO;
import com.diy.sigmund.diyuser.entity.vo.CustomOAuth2AccessToken;
import com.diy.sigmund.diyuser.mapper.UserAuthMapper;
import com.diy.sigmund.diyuser.mapper.UserBaseMapper;
import com.diy.sigmund.diyuser.service.UserAuthService;
import com.diy.sigmund.diyuser.service.UserBaseService;
import java.util.Date;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ylm-sigmund
 * @since 2021/8/30 17:48
 */
@Service
public class UserBaseServiceImpl implements UserBaseService {

    @Autowired
    private UserAuthMapper userAuthMapper;
    @Autowired
    private UserBaseMapper userBaseMapper;
    @Autowired
    private UserAuthService userAuthService;

    @Override
    public ResultMsg update(UserBaseDTO dto) {
        CustomUser context = ContextHolder.getInstance().getCustomUser();
        UserBase baseDO = new UserBase();
        BeanUtils.copyProperties(dto, baseDO);
        baseDO.setUpdateTime(new Date());
        baseDO.setUserId(context.getUserId());
        if (userBaseMapper.updateByPrimaryKeySelective(baseDO) < 1) {
            return ResultMsg.fail("更新用户基础信息失败");
        }
        // 查询用户授权信息
        UserAuth userAuth = userAuthMapper.getByIdentifier(context.getIdentifier());
        // 查询用户基础信息
        UserBase userBase = userBaseMapper.selectByPrimaryKey(userAuth.getUserId());
        CustomOAuth2AccessToken customOAuth2AccessToken = new CustomOAuth2AccessToken();
        customOAuth2AccessToken.setAccessToken(context.getAccessToken());
        customOAuth2AccessToken.setRefreshToken(context.getRefreshToken());
        ResultMsg resultMsg = userAuthService.buildCustomUserVO(userAuth, userBase, customOAuth2AccessToken);
        return ResultMsg.success(resultMsg);
    }
}
